/**
 * 树结构转list结构
 * @param list 需要外部传入一个空的数组
 * @param tree 树结构的数据
 */
export function treeToList (tree, list = []) {
  tree.forEach(node => {
    list.push(node)
    if (node.children && node.children.length) {
      treeToList(node.children, list)
    }
  })
  return list
}

/**
 * list结构转树结构
 * @param list
 */
export function listToTree (list, key = 'id', rootNodeParent = 0) {
  // 过滤出没有父级节点的节点
  const rootNodes = list.filter(node => {
    return !list.some(node2 => node2[key] === node.parent)
  })
  // 找出所有子节点
  rootNodes.forEach(node => {
    node.parent = rootNodeParent
    node.parents = `${rootNodeParent},`
    node.children = findChildren(list, node[key], key)
  })
  return rootNodes
}

/**
 * 递归查找下级节点
 */
function findChildren (list, parent, key = 'id') {
  const subNodes = list.filter(node => node.parent === parent)
  subNodes.forEach(node => {
    node.children = findChildren(list, node[key])
  })
  return subNodes
}

export function findNodeInTree(tree,targetId){
  let result = tree.find(node=> node.id === targetId)
  if(result!==undefined){
    return result
  }else{
    let subNodes = tree.map(n=>n.children).flat()
    if(subNodes.length===0){
      return undefined
    }else{
      return findNodeInTree(subNodes,targetId)
    }
  }

}
